package cn.dhn_app.horseman_app;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;

import net.sf.json.JSONObject;

/**
 * 小程序二维码带参数生成
 *
 */
public class AppletsQrCodeUtil {

    private static Logger log = Logger.getLogger(AppletsQrCodeUtil.class);


    public static String postToken() throws Exception {
        String APIKEY = "wx51d55df222d9901e";//小程序id
        String SECRETKEY = "5f71b93e3a56d190c10c8612fc1eb5fb";//小程序密钥
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APIKEY+"&secret="+SECRETKEY;
        URL url = new URL(requestUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes("");
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        if (requestUrl.contains("nlp"))
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        else
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
        String accesstoken=jsonObject.getString("access_token");
        return accesstoken;
    }

    /**
     * 生成带参小程序二维码
     * @param sceneStr 参数
     * @param accessToken token
     * @param fileDir 存放目录
     * @param fileName 文件名称（不含后缀）
     * @param format  二维码图片格式，jpg/png
     */
    private static void getminiqrQr(String sceneStr, String accessToken, String fileDir, String fileName, String format) {
        try
        {
            String url = ("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);

            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", sceneStr);
            paramJson.put("page", "pages/index/index"); // 这里特别注意前面不要加 '/'
            paramJson.put("width", 430);
            paramJson.put("auto_color", true); // 自动配置线条颜色
            paramJson.put("is_hyaline", true); // 背景色透明
            /**
             * line_color生效
             * paramJson.put("auto_color", false);
             * JSONObject lineColor = new JSONObject();
             * lineColor.put("r", 0);
             * lineColor.put("g", 0);
             * lineColor.put("b", 0);
             * paramJson.put("line_color", lineColor);
             * */

            InputStream is = getQRCodeInputStream(url, paramJson.toString());

            System.err.println("is数据："+is);

            System.err.println("paramJson.toString()数据："+paramJson.toString());

            File file = getFileByInputStream(is, fileDir, fileName + "." + format);
            file.createNewFile();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private static InputStream getQRCodeInputStream(String strURL, String params) {
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.connect();

            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码



            out.append(params);
            out.flush();
            out.close();
            InputStream is = connection.getInputStream();

            return is;

        } catch (IOException e) {
            return null;
        }
    }

    private static File getFileByInputStream(InputStream is, String filePath, String fileName) {

        // 构造文件目录，若目录不存在，则创建目录
        if (!new File(filePath).exists()) {
            new File(filePath).mkdirs();
        }

        System.out.println(filePath);
        System.out.println(fileName);

        File file=null;
        if(is!= null&& !org.apache.commons.lang.StringUtils.isEmpty(filePath)&&!org.apache.commons.lang.StringUtils.isEmpty(fileName)){
            try {
                file=new File(filePath,fileName);//可以是任何图片格式.jpg,.png等
                FileOutputStream fos=new FileOutputStream(file);
                byte[] b = new byte[1024];
                int nRead = 0;
                while ((nRead = is.read(b)) != -1) {
                    fos.write(b, 0, nRead);
                }
                fos.flush();
                fos.close();
            } catch (IOException e) {
            }
        }
        return file;
    }


    public static void main(String[] args) throws Exception {
        String accesstoken = postToken();
        System.out.println("accesstoken="+accesstoken);
        getminiqrQr("1", accesstoken, "D:\\", "小程序二维码", "jpg");

        // 注意：小程序必须正式发布且页面路径存在才可以生成
        // 如果保存文件为 1kb 时说明失败了，使用编码工具打开看里面的json错误信息对应去微信文档查看解决
    }
}